<template>
  <div class="user-head">
    <img
      ref="img"
      width="50px"
      :key="Math.random().toString()"
      :class="'newimage-' + avatar.id"
      style="width: 50px; height: 50px"
    />
    <canvas
      style="display: none"
      :key="Math.random().toString()"
      :class="'canvas-' + avatar.id"
      width="100"
      height="100"
    >
    </canvas>
  </div>
</template>
<style lang="scss" scope>
.user-head img {
  border-radius: 50%;
}
</style>
<script>
export default {
  data () {
    return {
      // id: Math.random().toString()
    }
  },
  props: {
    avatar: {
      default: {
        id: 0,
        username: '默',
        txcolor: 'white',
        bgcolor: 'blue'
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      const username = this.avatar.username ? this.avatar.username.substring(0, 1) : ''
      this.newImage(
        '.newimage-' + this.avatar.id,
        '.canvas-' + this.avatar.id,
        username,
        this.avatar.txcolor,
        this.avatar.bgcolor
      )
    })
  },
  methods: {
    newImage (igname, cname, text, txcolor, bgcolor) {
      // 生成图片
      var imageBox = document.querySelector(igname)
      var canvas = document.querySelector(cname)

      var cxt = canvas.getContext('2d')

      var img = new Image()
      img.src = require('@/assets/user.png')

      // 图片加载完成，才可处理
      img.onload = () => {
        // 画图(这里画布与图片等宽高)
        cxt.drawImage(img, 0, 0)
        // 设置字体大小
        cxt.font = '40px Microsoft YaHei'
        // 更改字号后，必须重置对齐方式，否则居中麻烦。设置文本的垂直对齐方式
        cxt.textBaseline = 'middle'
        cxt.textAlign = 'center'
        // 距离左边的位置
        var left = canvas.width / 2
        // 距离上边的位置 (图片高-文字距离图片底部的距离)
        // var top = canvas.height * 0.14
        // 文字颜色
        cxt.fillStyle = txcolor
        // 文字在画布的位置
        cxt.fillText(text, left, left)
        imageBox.src = canvas.toDataURL('image/jpg')
        // console.log(canvas.toDataURL('image/jpg'))
        // this.flag = 1
        imageBox.style.backgroundColor = bgcolor
      }
    }
  }
}
</script>
